package com.clip.appaction;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.clip.action.util.SessionAttributeKey;
import com.clip.entity.Contact;
import com.clip.entity.ContactGroup;
import com.clip.entity.ContactGroupMapping;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.Userassina;
import com.clip.entity.Usermobileinfo;
import com.clip.entity.appcontact.AppContact;
import com.clip.entity.appcontact.AppEmail;
import com.clip.entity.appcontact.AppPhone;
import com.clip.entity.appcontact.AppWeibo;
import com.clip.service.ContactGroupService;
import com.clip.service.ContactService;
import com.clip.service.UserDevicetokenSerivce;
import com.clip.service.UserService;
import com.clip.service.UsermobileinfoService;
import com.clip.util.MD5Util;
import com.clip.util.Struts2Utils;
import com.clip.util.ToolsUtils;
import com.clip.util.json.JSONArray;
import com.clip.util.json.JSONObject;
import com.clip.util.json.parser.JSONParser;
import com.clip.util.json.parser.ParseException;
import com.clip.util.mobile.HttpResponseXmlAnalyze;
import com.clip.util.mobile.MobileHttpSender;
import com.clip.util.mobile.MobileMsgPattern;
import com.clip.util.verifycode.VerifyCode;
import com.sun.org.apache.regexp.internal.REUtil;

@Controller
@Scope("prototype")
public class UserAppAction {
	@Autowired
	private UserService userService;
	@Autowired
	private ContactGroupService contactGroupService;
	@Autowired
	private	ContactService contactService; 
	@Autowired
	private UserDevicetokenSerivce devicetokenSerivce;
	@Autowired
	private UsermobileinfoService usermobileinfoService;
	private int SUCCESS=10000;
	private int FAILED=10001;
	private int PARAMERROR=10011;
	
	private int USERSUBSCRIBEDPAGELENGTH=10;
	private int RECOMMENDUSERSPAGELENGTH=10;
	
	private final String emailRegex="^([\\w\\-\\.]+)@((\\[([0-9]{1,3}\\.){3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))$";
	public void getUserInfo(){
		User user=this.userService.getUserById(uid);
		List userlogolist=this.userService.getUserLogoByUid(uid);
		JSONObject returnObj=new JSONObject();
		if(user!=null&&user.getStatus()==1){
			returnObj.put("result", SUCCESS);
			returnObj.put("name", user.getName());
			returnObj.put("sex", user.getSex()==null?0:user.getSex());
			returnObj.put("QQ", user.getQq()==null?"":user.getQq());
			returnObj.put("email", user.getEmail()==null?"":user.getEmail());
			returnObj.put("smalllogo", userlogolist.get(1));
			returnObj.put("biglogo", userlogolist.get(0));
			returnObj.put("birth",user.getBirth()==null?0l:user.getBirth());
			returnObj.put("living", user.getLiving()==null?"":user.getLiving());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void updateUserInfo(){
		if(uid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		if(currentUser!=null&&currentUser.getStatus()==1){
			if(name!=null&&name.length()>0)
				currentUser.setName(name);
			if(qq!=null&&qq.length()>0)
				currentUser.setQq(qq);
			currentUser.setSex(sex);
			if(living!=null&&living.length()>0)
				currentUser.setLiving(living);
//			if(password!=null&&password.length()>0)
//				currentUser.setPwd(ToolsUtils.getStringForMD5(password));
			currentUser=this.userService.updateUser(currentUser);
			
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void updateUserAvatar(){
		if(uid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		if(this.avatarPic!=null){
			String md5 =null;
			try {
				md5 = MD5Util.getFileMD5String(avatarPic);
			} catch (IOException e) {
				e.printStackTrace();
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "图片文件异常");
				Struts2Utils.renderJson(returnObj.toJSONString());
				return;
			}
			if(!md5.equals(avatarmd5)){
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "图片文件异常");
				Struts2Utils.renderJson(returnObj.toJSONString());
				return;
			}
			this.userService.updateAvatar(uid,this.avatarPic);
			returnObj.put("result", SUCCESS);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "上传的图片不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		
	}
	
	public void login(){
		User user=this.userService.getUserByEmail(username);
		JSONObject returnObj=new JSONObject();
		if(user==null){
			returnObj.put("result", 10001);
			returnObj.put("errormsg", "账号或密码错误");
		}else{
			if(user.getPwd().equals(ToolsUtils.getStringForMD5(password))){
				HttpSession session = ServletActionContext.getRequest().getSession();
				session.setAttribute(SessionAttributeKey.USER, user);
				returnObj.put("result", SUCCESS);
				returnObj.put("uid", user.getId());
				returnObj.put("status", user.getStatus());
				if(user.getStatus()==0){
					String validatenum=null;
					if(user.getUserstatus()==null||user.getUserstatus().length()<=0){
						validatenum=VerifyCode.getValidateNumber();
						user.setUserstatus(validatenum);
						this.userService.updateUser(user);
					}else
						validatenum=user.getUserstatus();
					if(user.getEmail().matches(emailRegex)==false){
						int result=sendMobileMsg(user.getEmail(),user.getName(),validatenum);
						if(result==0){
							returnObj.put("validatenum", validatenum);
							returnObj.put("codesendtype", 2);
						}else{
							returnObj=new JSONObject();
							returnObj.put("result", FAILED);
							returnObj.put("errormsg", "发送验证码失败");
						}
					}else{
						this.userService.sendAppActivateEmail(user,validatenum);
						returnObj.put("validatenum", validatenum);
						returnObj.put("codesendtype", 1);
					}
				}
			}else{
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "账号或密码错误");
			}
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void getUserGroups(){
		User user=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(user!=null&&user.getStatus()==1){
			returnObj.put("result", SUCCESS);
			List list=this.contactGroupService.getUserGroups(user.getId());
			JSONArray array=new JSONArray();
			for (Object object : list) {
				ContactGroup contactGroup=(ContactGroup) object;
				JSONObject temp=new JSONObject();
				temp.put("groupname", contactGroup.getGroupname());
				temp.put("pinyingroupname", contactGroup.getPinyingroupname());
				temp.put("groupid", contactGroup.getId());
				temp.put("membercount", contactGroup.getMembercount());
				array.add(temp);
			}
			returnObj.put("groups", array);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void getUserAllContactsAndGroups(){
		User user=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(user!=null&&user.getStatus()==1){
			returnObj.put("result", SUCCESS);
			List list=this.contactService.getContactByUid(uid,null,-1);
			JSONArray array=new JSONArray();
			for (Object object : list) {
				Contact contact=(Contact) object;
				JSONObject temp=new JSONObject();
				temp.put("contactname", contact.getName());
				temp.put("contactemail", contact.getContactemail());
				temp.put("contactpinyinname", contact.getPinyinname());
				temp.put("contactuid", contact.getContactuid());
				List userlogolist=this.userService.getUserLogoByUid(contact.getContactuid());
				temp.put("smalllogo", userlogolist.get(1));
				temp.put("biglogo", userlogolist.get(0));
				array.add(temp);
			}
			returnObj.put("contacts", array);
			List contactgrouplist=this.contactGroupService.getUserGroups(user.getId());
			JSONArray array2=new JSONArray();
			for (Object object : contactgrouplist) {
				ContactGroup contactGroup=(ContactGroup) object;
				JSONObject temp=new JSONObject();
				if(contactGroup.getMembercount()==0)
					continue;
				temp.put("groupname", contactGroup.getGroupname());
				temp.put("pinyingroupname", contactGroup.getPinyingroupname());
				temp.put("groupid", contactGroup.getId());
				temp.put("membercount", contactGroup.getMembercount());
				List templist=this.contactGroupService.loadContactsInsideGroup(uid, contactGroup.getId());
				JSONArray array3=new JSONArray();
				for (Object contactuidobj : templist) {
					JSONObject temp3=new JSONObject();
					int contactuid=(Integer) contactuidobj;
					temp3.put("contactuid",contactuid);
					array3.add(temp3);
				}
				temp.put("groupcontacts", array3);
				array2.add(temp);
			}
			returnObj.put("groups", array2);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void getUserContacts(){
		User user=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(user!=null&&user.getStatus()==1){
			returnObj.put("result", SUCCESS);
			List list=this.contactService.getContactByUid(uid,groupids,-1);
			if(list==null){
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "数据错误");
				Struts2Utils.renderJson(returnObj.toJSONString());
				return;
			}
			JSONArray array=new JSONArray();
			for (Object object : list) {
				Contact contact=(Contact) object;
				JSONObject temp=new JSONObject();
				temp.put("contactname", contact.getName());
				temp.put("contactemail", contact.getContactemail());
				temp.put("contactpinyinname", contact.getPinyinname());
				temp.put("contactuid", contact.getContactuid());
				List userlogolist=this.userService.getUserLogoByUid(contact.getContactuid());
				temp.put("smalllogo", userlogolist.get(1));
				temp.put("biglogo", userlogolist.get(0));
				array.add(temp);
			}
			returnObj.put("contacts", array);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	/**
	 * 请求好友/添加好友
	 */
	public void addUserContacts(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}else{
			this.contactService.addUserContacts(currentUser,uids);
			returnObj.put("result", SUCCESS);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}
	}

	public void getContactInfo(){
		JSONObject returnObj=new JSONObject();
		if(uid==0||vuid==0){
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User visitUser=this.userService.getUserById(vuid);
		returnObj.put("result", SUCCESS);
		if(visitUser.getUsertype()==1){
			returnObj.put("usertype", 1);
			boolean isfriend=this.contactService.judgeRelation(vuid, uid);
			returnObj.put("isfriend", isfriend);
			returnObj.put("name", visitUser.getName());
			returnObj.put("sex", visitUser.getSex());
			returnObj.put("qq", visitUser.getQq());
			returnObj.put("email", visitUser.getEmail());
			returnObj.put("birth", visitUser.getBirth());
			List templist=this.userService.getUserLogoByUid(visitUser.getId());
			returnObj.put("userlogo",templist.get(0));
			returnObj.put("smalluserlogo",templist.get(1));
		}else{
			returnObj.put("usertype", 2);
			returnObj.put("name", visitUser.getName());
			returnObj.put("job", visitUser.getJob());
			returnObj.put("blog", visitUser.getBlog());
			returnObj.put("userstatus", visitUser.getUserstatus());
			List templist=this.userService.getUserLogoByUid(visitUser.getId());
			returnObj.put("userlogo",templist.get(0));
			returnObj.put("smalluserlogo",templist.get(1));
			returnObj.put("issubsribed", this.userService.checkIsSubscribed(uid,vuid));
			returnObj.put("subscribedcount", this.contactService.countAllSubscribedUsers(visitUser.getId()));
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}

	/**
	 * 响应用户请求
	 */
	public void responseContactRequest(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}else{
			this.contactService.addContacts(currentUser,requestuids,responsestatus);
			returnObj.put("result", SUCCESS);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}
	}

	public void getSubscribedList(){
		List list=this.userService.getUserSubscribed(uid,needpagenum,this.USERSUBSCRIBEDPAGELENGTH);
		JSONObject returnObj=new JSONObject();
		returnObj.put("result", SUCCESS);
		JSONArray array=new JSONArray();
		for (Object object : list) {
			User user=(User) object;
			String name=user.getName();
			int uid=user.getId();
			long subscribedcount=this.contactService.countAllSubscribedUsers(user.getId());
			List headlist=this.userService.getUserLogoByUid(user.getId());
			String smalllogo=(String) headlist.get(1);
			JSONObject temp=new JSONObject();
			temp.put("name", name);
			temp.put("uid", uid);
			temp.put("subscribedcount", subscribedcount);
			temp.put("smalllogo", smalllogo);
			array.add(temp);
		}
		returnObj.put("subscribedusers", array);
		Struts2Utils.renderJson(returnObj.toJSONString());
	}

	public void getRecommendUsersList(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}else{
			List list=this.userService.getRecommendUsersList(needpagenum,this.RECOMMENDUSERSPAGELENGTH);
			returnObj.put("result", SUCCESS);
			JSONArray array=new JSONArray();
			for (Object object : list) {
				User user=(User) object;
				String name=user.getName();
				int ccuid=user.getId();
				String desc=user.getJob();
				long subscribedcount=this.contactService.countAllSubscribedUsers(user.getId());
				List headlist=this.userService.getUserLogoByUid(user.getId());
				String smalllogo=(String) headlist.get(1);
				JSONObject temp=new JSONObject();
				temp.put("name", name);
				temp.put("uid", ccuid);
				temp.put("subscribedcount", subscribedcount);
				temp.put("smalllogo", smalllogo);
				temp.put("desc", desc);
				boolean issubscribed=this.userService.checkIsSubscribed(uid, ccuid);
				temp.put("issubscribed", issubscribed);
				array.add(temp);
			}
			returnObj.put("recommendusers", array);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}
	}

	public void searchUsers(){
		if(uid==0||searchkey==null||searchkey.length()==0||usertype==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}else{
			List list=this.userService.searchUserByName(searchkey, currentUser, usertype);
			returnObj.put("result", SUCCESS);
			JSONArray array=new JSONArray();
			if(usertype==2){
				for (Object object : list) {
					User user=(User) object;
					JSONObject jsonObject=new JSONObject();
					jsonObject.put("name", user.getName());
					jsonObject.put("uid", user.getId());
					jsonObject.put("desc", user.getJob());
					List headlist=this.userService.getUserLogoByUid(user.getId());
					String smalllogo=(String) headlist.get(1);
					jsonObject.put("smalllogo", smalllogo);
					jsonObject.put("issubscribed", this.userService.checkIsSubscribed(currentUser.getId(), user.getId()));
					jsonObject.put("subscribedcount", this.contactService.countAllSubscribedUsers(user.getId()));
					array.add(jsonObject);
				}
			}else{
				for (Object object : list) {
					User user=(User) object;
					JSONObject jsonObject=new JSONObject();
					jsonObject.put("name", user.getName());
					jsonObject.put("uid", user.getId());
					List headlist=this.userService.getUserLogoByUid(user.getId());
					String smalllogo=(String) headlist.get(1);
					jsonObject.put("smalllogo", smalllogo);
					jsonObject.put("sex",user.getSex());
					jsonObject.put("birth",user.getBirth());
					boolean isfriend=this.contactService.judgeRelation(user.getId(), currentUser.getId());
					jsonObject.put("isfriend",isfriend);
					array.add(jsonObject);
				}
			}
			returnObj.put("users", array);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}
	}

	public void subscribeUser(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser!=null&&currentUser.getStatus()==1){
			this.contactService.subscribeCC(ccuid, currentUser);
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}

	public void unsubscribeUser(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser!=null&&currentUser.getStatus()==1){
			this.contactService.unsubscribeCC(ccuid, currentUser);
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}

	public void updateDevicetoken(){
		if(uid==0||devicetoken==null||devicetoken.length()==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		String result=this.devicetokenSerivce.updateUserDevicetoken(uid,devicetoken);
		JSONObject returnObj=new JSONObject();
		if(result==null){
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", result);
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void register(){
		int flag = 0;
		String msg = "";
		String pwdRegex="^[a-zA-Z0-9][a-zA-Z0-9_-]{5,19}$";
		if(username==null){
			flag = -1;
			msg = "请输入账号名";
		}else if(password==null){
			flag = -2;
			msg = "请输入密码";
		}else if(name==null){
			flag = -2;
			msg = "请输入昵称";
		}
		JSONObject returnobj=new JSONObject();
		if(flag>=0){
			if(password.matches(pwdRegex)){
				
				if(username.matches(emailRegex)==false){
					boolean isbind=usermobileinfoService.isMobileBindable(username);
					if(isbind==false){
						User user = userService.appReigster(username,ToolsUtils.htmlEnCode(name),password,sex,birth);
						if(user!=null){
							String validatenum=VerifyCode.getValidateNumber();
							user.setUserstatus(validatenum);
							this.userService.updateUser(user);
							int result=sendMobileMsg(user.getEmail(),user.getName(),validatenum);
							if(result==0){
								returnobj.put("result", SUCCESS);
								returnobj.put("uid", user.getId());
								returnobj.put("validatenum", validatenum);
							}else{
								returnobj.put("result", FAILED);
								returnobj.put("errormsg", "发送手机验证码失败");
							}
						}else{
							returnobj.put("result", FAILED);
							returnobj.put("errormsg", "用户名已存在");
						}
						
					}else{
						returnobj.put("result", FAILED);
						returnobj.put("errormsg", "手机号已被绑定");
					}
				}else{
					User user = userService.appReigster(username,ToolsUtils.htmlEnCode(name),password,sex,birth);
					if(user!=null){
						String validatenum=VerifyCode.getValidateNumber();
						user.setUserstatus(validatenum);
						this.userService.updateUser(user);
						this.userService.sendAppActivateEmail(user,validatenum);
						returnobj.put("result", SUCCESS);
						returnobj.put("uid", user.getId());
						returnobj.put("validatenum", validatenum);
					}else{
						returnobj.put("result", FAILED);
						returnobj.put("errormsg", "用户名已存在");
					}
				}
			}
		}else{
			returnobj.put("result", FAILED);
			returnobj.put("errormsg", msg);
		}
		Struts2Utils.renderJson(returnobj.toJSONString());
	}
	
	private int sendMobileMsg(String mobilenum,String name,String validatenum){
		System.out.println("验证码：validatenum="+validatenum);
		return 0;
//		String content=MobileHttpSender.sendMobileMsg(mobilenum, MobileMsgPattern.getAppMobileBundlingMsg(name, validatenum));
//		int result=HttpResponseXmlAnalyze.getSendResult(content);
//		return result;
	}
	
	public void resendMobilecode(){
		JSONObject returnobj=new JSONObject();
		User unvalidateUser=this.userService.getUserById(uid);
		if(unvalidateUser!=null&&unvalidateUser.getStatus()==0){
			String validatenum=VerifyCode.getValidateNumber();
			String emailRegex="^([\\w\\-\\.]+)@((\\[([0-9]{1,3}\\.){3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))$";
			Calendar now=Calendar.getInstance();
			int result=-1;
			if(unvalidateUser.getEmail().matches(emailRegex)){
				this.userService.sendAppActivateEmail(unvalidateUser,validatenum);
				result=0;
			}else{
				result=sendMobileMsg(unvalidateUser.getEmail(),unvalidateUser.getName(),validatenum);
			}
			if(result==0){
				returnobj.put("result", SUCCESS);
				returnobj.put("validatenum", validatenum);
			}else{
				returnobj.put("result", FAILED);
				returnobj.put("errormsg", "发送手机验证码失败");
			}
		}else{
			returnobj.put("result", FAILED);
			returnobj.put("errormsg", "用户不存在或已激活");
		}
		Struts2Utils.renderJson(returnobj.toJSONString());
	}
	
	public void activateUser(){
		JSONObject returnobj=new JSONObject();
		User unvalidateUser=this.userService.getUserById(uid);
		if(unvalidateUser!=null&&unvalidateUser.getStatus()==0){
			this.userService.activateUser(unvalidateUser);
			returnobj.put("result", SUCCESS);
		}else{
			returnobj.put("result", FAILED);
			returnobj.put("errormsg", "用户不存在");
		}
		Struts2Utils.renderJson(returnobj.toJSONString());
	}
	
	public void checkExistUsername(){
		JSONObject returnobj=new JSONObject();
		boolean flag=this.userService.checkExistUsername(username);
		if(flag==true){
			returnobj.put("result", FAILED);
		}else{
			returnobj.put("result", SUCCESS);
		}
		Struts2Utils.renderJson(returnobj.toJSONString());
	}
	
	public void checkPhoneContact(){
		JSONObject returnObj=new JSONObject();
		JSONObject parserObj=null;
		try {
			parserObj=(JSONObject) new JSONParser().parse(contacts);
		} catch (ParseException e) {
			e.printStackTrace();
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "数据错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(((Long)parserObj.get("uid")).intValue());
		if(currentUser!=null&&currentUser.getStatus()==1){
			JSONArray array=(JSONArray) parserObj.get("contacts");
			List<AppContact> list=this.contactService.analyzeContactsJSONArray(uid,array);
			JSONArray array2=new JSONArray();
			for (AppContact appContact : list) {
				JSONObject object=new JSONObject();
				object.put("name",appContact.getName());
				if(appContact.getKey()!=null&&appContact.getKey().length()>0)
					object.put("key", appContact.getKey());
				JSONArray emails=new JSONArray();
				JSONArray phones=new JSONArray();
				JSONArray weibos=new JSONArray();
				for (AppEmail email : appContact.getEmails()) {
					JSONObject temp=new JSONObject();
					temp.put("email", email.getEmail());
					temp.put("uid", email.getUid());
					temp.put("isfriend", email.isIsfriend());
					emails.add(temp);
				}
				for (AppPhone phone : appContact.getPhones()) {
					JSONObject temp=new JSONObject();
					temp.put("mobile", phone.getPhonenum());
					temp.put("uid", phone.getUid());
					temp.put("isfriend", phone.isIsfriend());
					phones.add(temp);
				}
				for (AppWeibo weibo : appContact.getWeibos()) {
					JSONObject temp=new JSONObject();
					temp.put("sinauid", weibo.getSinauid());
					temp.put("uid", weibo.getUid());
					temp.put("isfriend", weibo.isIsfriend());
					weibos.add(temp);
				}
				if(emails.size()>0)
					object.put("emails", emails);
				if(phones.size()>0)
					object.put("mobiles", phones);
				if(weibos.size()>0)
					object.put("sinas", weibos);
				array2.add(object);
			}
			returnObj.put("result", SUCCESS);
			returnObj.put("contacts", array2);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
		}
		
	}
	
	public void sinaRegister(){
		User user=this.userService.sinaRegister(sinauid,accessToken,name,username,password,avatar,sex,birth,sinaemail);
		JSONObject returnObj=new JSONObject();
		returnObj.put("result", SUCCESS);
		returnObj.put("uid", user.getId());
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void checkSinaContact(){
		JSONObject returnObj=new JSONObject();
		JSONObject parserObj=null;
		try {
			parserObj=(JSONObject) new JSONParser().parse(contacts);
		} catch (ParseException e) {
			e.printStackTrace();
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "数据错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById((Integer)parserObj.get("uid"));
		if(currentUser!=null&&currentUser.getStatus()==1){
			JSONArray array=(JSONArray) parserObj.get("contacts");
			this.userService.checkSinaContact(currentUser.getId(),array);
			returnObj.put("result", SUCCESS);
			returnObj.put("contacts", array);
			Struts2Utils.renderJson(returnObj.toJSONString());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
		}
	}
	
	public void getUserSinatoken(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser!=null&&currentUser.getStatus()==1){
			Userassina userassina=this.userService.getUserSinatoken(uid);
			if(userassina!=null){
				returnObj.put("result", SUCCESS);
				returnObj.put("sinauid", userassina.getSinauid());
				returnObj.put("accessToken", userassina.getAccessToken());
			}else{
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "微博授权信息不存在");
			}
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void updateUserSinatoken(){
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser!=null&&currentUser.getStatus()==1){
			this.userService.updateUserSinatoken(uid, accessToken);
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void deleteContact(){
		if(uid==0||vuid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		String str=contactService.delContactByUid(currentUser,vuid);
		if(str.indexOf("flag:1")>0){
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "删除错误");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
		
	}
	
	public void getExistCircles(){
		if(uid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		returnObj.put("result", SUCCESS);
		JSONArray array=new JSONArray();
		List list=this.contactGroupService.getExistCircles(currentUser.getId());
		if(list!=null){
			for (int i = 0; i < list.size(); i++) {
				ContactGroup contactGroup=(ContactGroup) list.get(i);
				JSONObject temp2=new JSONObject();
				temp2.put("circlename", contactGroup.getGroupname());
				temp2.put("pinyincirclename", contactGroup.getPinyingroupname());
				temp2.put("memebercount", contactGroup.getMembercount());
				temp2.put("circleid",contactGroup.getId());
				array.add(temp2);
			}
		}
		returnObj.put("circles", array);
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void createCircle(){
		if(uid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		int groupid=this.contactGroupService.createContactGroup(this.circlename,currentUser);
		if(groupid==0){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "对不起，群组名字已经存在。");
		}else{
			returnObj.put("result", SUCCESS);
			returnObj.put("circleid", groupid);
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void loadUsersInsideCircle(){
		if(uid==0||circleid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		returnObj.put("result", SUCCESS);
		List contactuidslist=this.contactGroupService.loadContactsInsideGroup(currentUser.getId(), this.circleid);
		JSONArray array=new JSONArray();
		for (Object object : contactuidslist) {
			int contactuid=(Integer)object;
			Contact con=(Contact)this.contactGroupService.getContactByUids(currentUser.getId(),contactuid);
			JSONObject map=new JSONObject();
			map.put("contactid", con.getId());
			map.put("name", con.getName());
			map.put("username", con.getContactemail());
			map.put("uid", con.getContactuid());
			String smalllogo=(String) UserService.getUserLogoByUid(con.getContactuid()).get(1);
			map.put("ulogo",ToolsUtils.xmlCDATA(smalllogo));
			array.add(map);
		}
		returnObj.put("contacts", array);
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void loadUsersOutsideCircle(){
		if(uid==0||circleid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		returnObj.put("result", SUCCESS);
		List contactuidslist=this.contactGroupService.loadContactsInsideGroup(currentUser.getId(), this.circleid);
		List<Contact> contactlist=this.contactService.getCurrentUserContacts(currentUser.getId(),contactuidslist);
		JSONArray array=new JSONArray();
		for (Contact con : contactlist) {
			JSONObject map=new JSONObject();
			map.put("contactid", con.getId());
			map.put("name", con.getName());
			map.put("username", con.getContactemail());
			map.put("uid", con.getContactuid());
			String smalllogo=(String) UserService.getUserLogoByUid(con.getContactuid()).get(1);
			map.put("ulogo",ToolsUtils.xmlCDATA(smalllogo));
			array.add(map);
		}
		returnObj.put("contacts", array);
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void addUsersToCircle(){
		if(uid==0||circleid==0||uids==null||uids.length()==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		boolean flag=this.contactGroupService.checkIsBelongToUser(currentUser.getId(),circleid);
		if(flag){
			ContactGroup circle=this.contactGroupService.addContacts2Group(circleid, uids);
			returnObj.put("result", SUCCESS);
			returnObj.put("circlename",circle.getGroupname());
			returnObj.put("membercount",circle.getMembercount());
			returnObj.put("circleid",circle.getId());
			Struts2Utils.renderJson(returnObj.toJSONString());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "该圈子不属于您");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
	}
	public void removeUsersFromCircle(){
		if(uid==0||circleid==0||uids==null||uids.length()==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		boolean flag=this.contactGroupService.checkIsBelongToUser(currentUser.getId(),circleid);
		if(flag){
			ContactGroup circle=this.contactGroupService.removeContactsFromGroup(circleid, uids);
			returnObj.put("result", SUCCESS);
			returnObj.put("circlename",circle.getGroupname());
			returnObj.put("membercount",circle.getMembercount());
			returnObj.put("circleid",circle.getId());
			Struts2Utils.renderJson(returnObj.toJSONString());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "该圈子不属于您");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
	}
	
	public void updateCircleName(){
		if(uid==0||circleid==0||circlename==null||circlename.length()==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		boolean flag=this.contactGroupService.checkIsBelongToUser(currentUser.getId(),circleid);
		if(flag){
			boolean issuccess=this.contactGroupService.updateGroupName(circleid, circlename);
			if(issuccess){
				returnObj.put("result", SUCCESS);
			}else{
				returnObj.put("result", FAILED);
				returnObj.put("errormsg","该圈子名已经存在");
			}
			Struts2Utils.renderJson(returnObj.toJSONString());
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "该圈子不属于您");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
	}
	
	public void deleteCircle(){
		if(uid==0||circleid==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		boolean flag=this.contactGroupService.deleteContactGroup(currentUser.getId(),circleid);
		if(flag){
			returnObj.put("result", SUCCESS);
		}else{
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "该圈子您无权操作或已被删除");
		}
		Struts2Utils.renderJson(returnObj.toJSONString());
	}
	
	public void updatePassword(){
		if(uid==0||password==null||password.length()==0||newpwd==null||newpwd.length()==0){
			JSONObject returnObj=new JSONObject();
			returnObj.put("result", PARAMERROR);
			returnObj.put("errormsg", "传入参数错误");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		User currentUser=this.userService.getUserById(uid);
		JSONObject returnObj=new JSONObject();
		if(currentUser==null||currentUser.getStatus()!=1){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "当前用户不存在");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}
		if(!ToolsUtils.getStringForMD5(password).equals(currentUser.getPwd())){
			returnObj.put("result", FAILED);
			returnObj.put("errormsg", "旧密码不正确，请重新输入。");
			Struts2Utils.renderJson(returnObj.toJSONString());
			return;
		}else{
			if(password.equals(newpwd)){
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "新密码 不能同旧密码一致。");
				Struts2Utils.renderJson(returnObj.toJSONString());
				return;
			}
			String pwdRegex="^[a-zA-Z0-9][a-zA-Z0-9_-]{5,19}";
			if(newpwd.matches(pwdRegex)){
				currentUser.setPwd(ToolsUtils.getStringForMD5(this.newpwd));
				this.userService.updateUser(currentUser);
				returnObj.put("result", SUCCESS);
				Struts2Utils.renderJson(returnObj.toJSONString());
				return;
			}else{
				returnObj.put("result", FAILED);
				returnObj.put("errormsg", "密码只能输入英文数字下划线及中横线");
				Struts2Utils.renderJson(returnObj.toJSONString());
				return;
			}
		}
	}
	
	private int uid;
	private String sinauid;
	private String sinaemail;
	
	private String username;
	private String password;
	private String name;
	private int sex;
	
	private String birth;
	
	private String qq;
	private String groupids;
	private int needpagenum;
	private String contacts;
	private String uids;
	private int vuid;
	private String requestuids; 
	private int responsestatus;//0拒绝 1接受
	private String devicetoken;
	private int ccuid;
	private String searchkey;
	private int usertype;
	private String accessToken;
	private String avatar;
	private File avatarPic;
	private String avatarmd5;
	private String living;
	private String circlename;
	private int circleid;
	private String newpwd;
	
	
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public String getQq() {
		return qq;
	}

	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getGroupids() {
		return groupids;
	}

	public void setGroupids(String groupids) {
		this.groupids = groupids;
	}

	public int getNeedpagenum() {
		return needpagenum;
	}

	public void setNeedpagenum(int needpagenum) {
		this.needpagenum = needpagenum;
	}

	public String getContacts() {
		return contacts;
	}

	public void setContacts(String contacts) {
		this.contacts = contacts;
	}

	public String getUids() {
		return uids;
	}

	public void setUids(String uids) {
		this.uids = uids;
	}

	public int getVuid() {
		return vuid;
	}

	public void setVuid(int vuid) {
		this.vuid = vuid;
	}

	public int getResponsestatus() {
		return responsestatus;
	}

	public void setResponsestatus(int responsestatus) {
		this.responsestatus = responsestatus;
	}

	public String getDevicetoken() {
		return devicetoken;
	}

	public void setDevicetoken(String devicetoken) {
		this.devicetoken = devicetoken;
	}

	public int getCcuid() {
		return ccuid;
	}

	public void setCcuid(int ccuid) {
		this.ccuid = ccuid;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getAvatar() {
		return avatar;
	}

	public void setAvatar(String avatar) {
		this.avatar = avatar;
	}

	public File getAvatarPic() {
		return avatarPic;
	}

	public void setAvatarPic(File avatarPic) {
		this.avatarPic = avatarPic;
	}

	public String getAvatarmd5() {
		return avatarmd5;
	}

	public void setAvatarmd5(String avatarmd5) {
		this.avatarmd5 = avatarmd5;
	}

	public String getLiving() {
		return living;
	}

	public void setLiving(String living) {
		this.living = living;
	}

	public String getRequestuids() {
		return requestuids;
	}

	public void setRequestuids(String requestuids) {
		this.requestuids = requestuids;
	}

	public String getSearchkey() {
		return searchkey;
	}

	public void setSearchkey(String searchkey) {
		this.searchkey = searchkey;
	}

	public int getUsertype() {
		return usertype;
	}

	public void setUsertype(int usertype) {
		this.usertype = usertype;
	}

	public String getCirclename() {
		return circlename;
	}

	public void setCirclename(String circlename) {
		this.circlename = circlename;
	}

	public int getCircleid() {
		return circleid;
	}

	public void setCircleid(int circleid) {
		this.circleid = circleid;
	}

	public String getNewpwd() {
		return newpwd;
	}

	public void setNewpwd(String newpwd) {
		this.newpwd = newpwd;
	}

	public String getBirth() {
		return birth;
	}

	public void setBirth(String birth) {
		this.birth = birth;
	}

	public String getSinauid() {
		return sinauid;
	}

	public void setSinauid(String sinauid) {
		this.sinauid = sinauid;
	}

	public String getSinaemail() {
		return sinaemail;
	}

	public void setSinaemail(String sinaemail) {
		this.sinaemail = sinaemail;
	}
	
	
	
}

